package com.dkha.server.controllers;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkha.common.enums.ApiUrlEnum;
import com.dkha.common.enums.ErrEnum;
import com.dkha.common.enums.SEXEnums;
import com.dkha.common.http.HttpUtil;
import com.dkha.common.modules.vo.ApiVO;
import com.dkha.common.modules.vo.face.*;
import com.dkha.common.modules.vo.position.PositionVO;
import com.dkha.common.modules.vo.warning.*;
import com.dkha.common.redis.RedisKeys;
import com.dkha.common.redis.RedisUtils;
import com.dkha.common.result.CommonResult;
import com.dkha.common.systemcode.SystemCode;
import com.dkha.common.util.Base64ImageUtils;
import com.dkha.common.util.DateUtils;
import com.dkha.common.util.TimeUtil;
import com.dkha.common.util.UtilValidate;
import com.dkha.server.mappers.FaceInformationMapper;
import com.dkha.server.modules.entities.*;
import com.dkha.server.modules.entities.faceCamera.FaceCameraInfo;
import com.dkha.server.services.*;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version V1.0
 * @Description: TODO(预警查询功能)
 * All rights 成都电科慧安
 * @Title: WarningController
 * @Package com.dkha.server.controllers
 * @author: panhui
 * @date: 2019/12/10 9:37
 * @Copyright: 成都电科慧安
 */
@RestController
@RequestMapping(value = "/warning")
@Api(tags = "预警查询")
@Slf4j
public class WarningController extends CommonResult {

    @Autowired
    private HttpUtil httpUtil;

    @Value("${api.server.prefix}")
    private String link;

    @Autowired
    private Gson gson;


    @Autowired
    private FaceCameraService faceCameraService;


    @GetMapping("/todayBayonet")//    {total}
    @ApiOperation(value = "今日抓拍/累计抓拍")
    public CommonResult todayBayonet() {
        BayonetReturnVO bayonetReturnVO = new BayonetReturnVO();
        //查询当日抓拍总数
        QueryWrapper<FaceInformation> queryWrapper1 = new QueryWrapper<>();
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd aHH:mm:ss:SSS");
        //获取当日的时间
        String start1 = dateFormatGmt.format(TimeUtil.toDayStart());
        String end1   = dateFormatGmt.format(TimeUtil.toDayStop());
        //当日抓拍条件查询
        queryWrapper1.ge("time",start1)
                .le("time",end1);
        bayonetReturnVO.setToDaySnapShot(faceInformationMapper.selectCount(queryWrapper1).longValue());
        //查询累计抓拍总数
        QueryWrapper<FaceInformation> queryWrapper2 = new QueryWrapper<>();
        bayonetReturnVO.setTotalSnapShot(faceInformationMapper.selectCount(queryWrapper2).longValue());
        return successResult(bayonetReturnVO);


    }

    @GetMapping("/todayBayonetBySize/{carmeraId}/{pageSize}")//    {total}
    @ApiOperation(value = "今日抓拍根據條數返回")
    public CommonResult todayBayonet(@PathVariable("carmeraId") String carmeraId, @PathVariable("pageSize") Integer pageSize) {
        if (UtilValidate.isEmpty(carmeraId)) {
            return failResult(SystemCode.ParaIsNull);
        }

        ApiAlarmVO apiAlarmVO = new ApiAlarmVO();
        apiAlarmVO.setCameraId(carmeraId);
        PageVO pageVO = new PageVO();
        pageVO.setPageSize(1);
        if (UtilValidate.isNotEmpty(pageSize)) {
            pageVO.setPageSize(pageSize);
        }
        pageVO.setStartTimestamp(TimeUtil.toDayStart());
        pageVO.setStopTimestamp(TimeUtil.toDayStop());
        apiAlarmVO.setPage(pageVO);
        try {
            ApiVO warningVO = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARM_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
//            BayonetReturnVO bayonetReturnVO = new BayonetReturnVO();
            BayoneReturnListVO bayoneReturnListVO = new BayoneReturnListVO();
            if (!UtilValidate.isEmpty(warningVO) && !UtilValidate.isEmpty(warningVO.getData())) {
                WarningBayonetReturnVO wvo = gson.fromJson(gson.toJson(warningVO.getData()), WarningBayonetReturnVO.class);
                //因为数据没有
                if (!UtilValidate.isEmpty(wvo.getResult()) && wvo.getResult().size() > 0) {

                    wvo.getResult().forEach(a ->
                    {
                        a.getFaces().forEach(ea ->
                        {
                            try {
                                if (redisUtils.exists(RedisKeys.getCameraSize(a.getCameraId()))) {
                                    BgImageSize bgImageSize = gson.fromJson(redisUtils.get(RedisKeys.getCameraSize(a.getCameraId())).toString(), BgImageSize.class);
                                    PositionVO positionVo = Base64ImageUtils.deelPostion(ea.getFaceRect(), bgImageSize.getBgWidth(), bgImageSize.getBgHeight());
                                    positionVo.setBgHeight(bgImageSize.getBgWidth());
                                    positionVo.setBgWidth(bgImageSize.getBgHeight());
                                    ea.setFaceRect(positionVo);
                                } else {
                                    BufferedImage bufferedImage = Base64ImageUtils.urlToBufferImage(new URL(a.getFaceBgUrl()));
                                    PositionVO positionVo = Base64ImageUtils.deelPostion(ea.getFaceRect(), bufferedImage.getWidth(), bufferedImage.getHeight());
                                    positionVo.setBgHeight(bufferedImage.getHeight());
                                    positionVo.setBgWidth(bufferedImage.getWidth());
                                    ea.setFaceRect(positionVo);
                                    redisUtils.set(RedisKeys.getCameraSize(a.getCameraId()), gson.toJson(new BgImageSize(a.getCameraId(), bufferedImage.getWidth(), bufferedImage.getHeight())));
                                    bufferedImage = null;
                                }
                            } catch (MalformedURLException e1) {
                            }
                        });
                    });

                    bayoneReturnListVO.setResult(wvo.getResult());
                    bayoneReturnListVO.setToDaySnapShot(wvo.getPage().getTotal());
                    //累计抓拍
                    pageVO.setStartTimestamp(null);
                    pageVO.setStopTimestamp(null);
                    //统计总数
                    apiAlarmVO.setPage(pageVO);
                    ApiVO wo = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARM_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
                    WarningBayonetReturnVO woVo = gson.fromJson(gson.toJson(wo.getData()), WarningBayonetReturnVO.class);
                    if (UtilValidate.isEmpty(woVo)) {
                        bayoneReturnListVO.setTotalSnapShot(0L);
                    } else {
                        bayoneReturnListVO.setTotalSnapShot(woVo.getPage().getTotal());
                    }
                } else {
                    bayoneReturnListVO.setToDaySnapShot(0L);
                    bayoneReturnListVO.setResult(new ArrayList<>());
                }
            }
            //累计抓拍
            pageVO.setStartTimestamp(null);
            pageVO.setStopTimestamp(null);
            //统计总数
            apiAlarmVO.setPage(pageVO);
            ApiVO wo = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARM_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
            WarningBayonetReturnVO wovo = gson.fromJson(gson.toJson(wo.getData()), WarningBayonetReturnVO.class);
            if (UtilValidate.isEmpty(wovo)) {
                bayoneReturnListVO.setTotalSnapShot(0L);
            } else {
                bayoneReturnListVO.setTotalSnapShot(wovo.getPage().getTotal());
            }
            return successResult(bayoneReturnListVO);
        } catch (Exception e) {
            e.printStackTrace();
            return failResult("查询异常：" + e.getMessage());
        }
    }


    @Autowired
    private IControlBayonetMidService iControlBayonetMidService;


    @ApiOperation(value = "卡口功能-打开卡口页面获取最新布控的一个摄像头id")
    @GetMapping("/bayonet")
    public CommonResult bayonetIndex() {
        //根据es查询当前数据
        ApiAlarmVO apiAlarmVO = new ApiAlarmVO();
        PageVO pageVO = new PageVO();
        pageVO.setPageSize(1);
        pageVO.setStartTimestamp(TimeUtil.toDayStart());
        pageVO.setStopTimestamp(TimeUtil.toDayStop());
        apiAlarmVO.setPage(pageVO);
        String cameraId = "";
        Map<String, String> myMap = new HashMap<>();
        try {
            ApiVO warningVO = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARM_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
            if (!UtilValidate.isEmpty(warningVO) && !UtilValidate.isEmpty(warningVO.getData())) {
                WarningBayonetReturnVO wvo = gson.fromJson(gson.toJson(warningVO.getData()), WarningBayonetReturnVO.class);
                //因为数据没有
                if (!UtilValidate.isEmpty(wvo.getResult()) && wvo.getResult().size() > 0) {
                    cameraId = wvo.getResult().get(0).getCameraId();
                }
            }
            if (UtilValidate.isEmpty(cameraId)) {
                ControlBayonetMid controlBayonetMid = iControlBayonetMidService.selectFaceCameraByTime();
                if (UtilValidate.isEmpty(controlBayonetMid)) {
                    return failResult(SystemCode.NO_DATA.code, SystemCode.NO_DATA.des, null);
                }
                cameraId = controlBayonetMid.getIdFaceCamera().toString();
            }
            FaceCameraInfo faceCameraInfo = faceCameraService.findById(new Long(cameraId));
            myMap.put("camera_region_firstlevel", faceCameraInfo.getCameraRegionFirstlevel());
            myMap.put("cameraId", cameraId);
            String name = faceCameraInfo.getCameraName();
            myMap.put("cameraName", (UtilValidate.isEmpty(name)) ? "摄像头" : name + "(摄像头)");
        } catch (Exception e) {
            return failResult("查询异常");
        }
        return successResult(myMap);
    }

    @ApiOperation(value = "卡口功能-查看全部")
    @PostMapping("/bayonet")
    public CommonResult bayonet(@ApiParam(required = true, name = "apiAlarmVO", value = "{\n" +
            "  \"cameraId\": \"摄像头id（可以空）\",\n" +
            "  \"page\": {\n" +
            "    \"order\": \"排序默认DESC\",\n" +
            "    \"pageNo\": 0,\n" +
            "    \"pageSize\": 0,\n" +
            "    \"startTimestamp\": 抓拍时间开始,\n" +
            "    \"stopTimestamp\": 抓拍时间结束\n" +
            "  }\n" +
            "}") @RequestBody ApiAlarmVO apiAlarmVO) {
        try {
//            System.out.println("----------");
            ApiVO warningVO = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARM_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
            if (UtilValidate.isEmpty(warningVO) || warningVO.getCode().intValue() == ErrEnum.NOT_FOUND.getCode().intValue()) {
                WarningPageVO warningPageVO = new WarningPageVO();
                return successResult(warningPageVO);
            }

            if (warningVO.getCode().intValue() != ErrEnum.OK.getCode().intValue()) {
                return failResult("服务器返回错误:" + warningVO.getMessage());
            }
            WarningBayonetReturnVO wvo = gson.fromJson(gson.toJson(warningVO.getData()), WarningBayonetReturnVO.class);
            //因为数据没有

            if (UtilValidate.isEmpty(wvo) || UtilValidate.isEmpty(wvo.getResult())) {
                return successResult(wvo);
            }

            try {
                wvo.getResult().forEach(a ->
                {
                    //更改为摄像头名称
                    FaceCameraInfo faceCameraInfo = faceCameraService.findById(new Long(a.getCameraId()));
                    String cameraId = a.getCameraId();
                    a.setCameraId(cameraId);
                    a.setCameraName((!UtilValidate.isEmpty(faceCameraInfo) ? faceCameraInfo.getCameraName() : cameraId));
                    a.setTimestamp(null);
                    a.getFaces().forEach(ea ->
                    {
                        if (UtilValidate.isEmpty(ea.getFeature())) {
                            ea.setFeature(new FeatureVO(-1, ""));
                        }
                        try {
                            if (redisUtils.exists(RedisKeys.getCameraSize(a.getCameraId()))) {
                                BgImageSize bgImageSize = gson.fromJson(redisUtils.get(RedisKeys.getCameraSize(a.getCameraId())).toString(), BgImageSize.class);
                                PositionVO positionVo = Base64ImageUtils.deelPostion(ea.getFaceRect(), bgImageSize.getBgWidth(), bgImageSize.getBgHeight());
                                positionVo.setBgHeight(bgImageSize.getBgWidth());
                                positionVo.setBgWidth(bgImageSize.getBgHeight());
                                ea.setFaceRect(positionVo);
                            } else {
                                BufferedImage bufferedImage = Base64ImageUtils.urlToBufferImage(new URL(a.getFaceBgUrl()));
                                PositionVO positionVo = Base64ImageUtils.deelPostion(ea.getFaceRect(), bufferedImage.getWidth(), bufferedImage.getHeight());
                                positionVo.setBgHeight(bufferedImage.getHeight());
                                positionVo.setBgWidth(bufferedImage.getWidth());
                                ea.setFaceRect(positionVo);
                                redisUtils.set(RedisKeys.getCameraSize(a.getCameraId()), gson.toJson(new BgImageSize(a.getCameraId(), bufferedImage.getWidth(), bufferedImage.getHeight())));
                                bufferedImage = null;
                            }
                        } catch (MalformedURLException e1) {
                        }
                    });
                });

            } catch (Exception ee) {
                log.error("卡口功能-查看全部:{}", ee.getMessage());
            }
            return successResult(wvo);
        } catch (Exception e) {
            return failResult("查询异常：" + e.getMessage());
        }
    }

    @Autowired
    private IControlTaskService iControlTaskService;

    @Autowired
    private IPortraitService iPortraitService;
    @Autowired
    private FaceInformationMapper faceInformationMapper;


    @Autowired
    private IFaceLibraryService iFaceLibraryService;


    @Autowired
    private RedisUtils redisUtils;

    @ApiOperation(value = "查看-预警信息")
    @PostMapping("/alarm")
    public CommonResult alarm(@ApiParam(required = true, name = "apiAlarmVO", value = "{\n" +
            "  \"page\": {\n" +
            "    \"order\": \"排序 默认DESC(默认可以不填)\",\n" +
            "    \"pageNo\": 0(默认1可以不填),\n" +
            "    \"pageSize\": 0(默认10可以不填),\n" +
            "    \"startTimestamp\": 0(默认可以不填查询所有),\n" +
            "    \"stopTimestamp\": 0(默认可以不填查询所有)\n" +
            "  },\n" +
            "  \"taskIds\": [任务id列表],\n" +
            "  \"cameraIds\": [摄像头列表],\n" +
            "  taskType:[任务类别:0 报警任务，1是视频任务不传默认为0]" +
            "}") @RequestBody ApiAlarmVO apiAlarmVO) {
//        try {
////            Long time=System.currentTimeMillis();
//            List<WarningPageVO> ararmList = new ArrayList<>();
//            ApiVO warningVO = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARMS_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
//            if (UtilValidate.isEmpty(warningVO) || warningVO.getCode().intValue() == ErrEnum.NOT_FOUND.getCode().intValue()) {
//                Page pages = new Page<>();
//                pages.setRecords(ararmList);
//                pages.setTotal(0);
//                return successResult(pages);
//            }
//            if (warningVO.getCode().intValue() != ErrEnum.OK.getCode().intValue()) {
//                return failResult("服务器返回错误:" + warningVO.getMessage());
//            }
//
//            WarningBayonetReturnVO wvo = gson.fromJson(gson.toJson(warningVO.getData()), WarningBayonetReturnVO.class);
//            if (UtilValidate.isEmpty(wvo)) {
//                return failResult("没有查询到数据");
//            }
//            wvo.getResult().forEach(a ->
//            {
////                a.getFaces() 存储时候进行拆分
//                if (!UtilValidate.isEmpty(a.getFaces()) && a.getFaces().size() > 0) {
//                    ApiFaceVO apiFaceVO = a.getFaces().get(0);
//                    try {
//                        if (redisUtils.exists(RedisKeys.getCameraSize(a.getCameraId()))) {
//                            BgImageSize bgImageSize = gson.fromJson(redisUtils.get(RedisKeys.getCameraSize(a.getCameraId())).toString(), BgImageSize.class);
//                            PositionVO positionVo = Base64ImageUtils.deelPostion(apiFaceVO.getFaceRect(), bgImageSize.getBgWidth(), bgImageSize.getBgHeight());
//                            positionVo.setBgHeight(bgImageSize.getBgHeight());
//                            positionVo.setBgWidth(bgImageSize.getBgWidth());
//                            apiFaceVO.setFaceRect(positionVo);
//                        } else {
//                            BufferedImage bufferedImage = Base64ImageUtils.urlToBufferImage(new URL(a.getFaceBgUrl()));
//                            PositionVO positionVo = Base64ImageUtils.deelPostion(apiFaceVO.getFaceRect(), bufferedImage.getWidth(), bufferedImage.getHeight());
//                            positionVo.setBgHeight(bufferedImage.getHeight());
//                            positionVo.setBgWidth(bufferedImage.getWidth());
//                            apiFaceVO.setFaceRect(positionVo);
//                            redisUtils.set(RedisKeys.getCameraSize(a.getCameraId()), gson.toJson(new BgImageSize(a.getCameraId(), bufferedImage.getWidth(), bufferedImage.getHeight())));
//                            bufferedImage = null;
//                        }
//                    } catch (MalformedURLException e1) {
//                    }
//
//
//                    WarningPageVO warningPageVO = new WarningPageVO();
//                    //根据任务区查询3
//                    //测试后期需要删除 TODO
////                    a.setTaskId("1204968766411169794");
//                    QueryWrapper<ControlTask> queryWrapper = new QueryWrapper<>();
//                    ControlTask controlTask = new ControlTask();
//                    controlTask.setTaskNo(a.getTaskId());
//                    queryWrapper.setEntity(controlTask);
//                    List<ControlTask> controlTaskList = iControlTaskService.getBaseMapper().selectList(queryWrapper);
//                    warningPageVO.setTaskId(a.getTaskId());
//                    if (!UtilValidate.isEmpty(controlTaskList) && controlTaskList.size() >= 1) {
//                        controlTask = controlTaskList.get(0);
//                        warningPageVO.setTaskName(controlTask.getTaskName());
////                        warningPageVO.setTaskType(ContralEnums.getTypeByValue(Integer.parseInt(controlTask.getDisposalType())).getMessage());
//                        warningPageVO.setTaskType(controlTask.getDisposalType());
//                    } else {
//                        warningPageVO.setTaskName("任务已删除");
//                        warningPageVO.setTaskType("");
//                    }
//                    //基本展示信息4-4
//                    warningPageVO.setBgImg(a.getFaceBgUrl());
//
//                    if (!UtilValidate.isEmpty(apiFaceVO.getCompare()) && apiFaceVO.getCompare().size() > 0) {
//                        ComparisonVO comparisonVO = apiFaceVO.getCompare().get(0);
//                        //库名称和库id0-2
//                        FaceLibrary faceLibrary = iFaceLibraryService.getBaseMapper().selectById(comparisonVO.getLibraryId());
//                        warningPageVO.setLibId(comparisonVO.getLibraryId());
//                        if (!UtilValidate.isEmpty(faceLibrary)) {
//                            warningPageVO.setLibName(faceLibrary.getFactoryName());
//                        } else {
//                            warningPageVO.setLibName(comparisonVO.getLibraryId());
//                        }
//                        warningPageVO.setScore(comparisonVO.getHitSimilarity());
//                        //查询人员信息 5-5
////                        comparisonVO.setComparisonFaceId("1204598824872067073");
//                        Portrait portrait = iPortraitService.getById(comparisonVO.getComparisonFaceId());
//                        if (!UtilValidate.isEmpty(portrait)) {
//                            if (UtilValidate.isNotEmpty(portrait.getName())) {
//                                warningPageVO.setName(portrait.getName());
//                            }
//                            if (UtilValidate.isNotEmpty(portrait.getBirthDate())) {
//                                warningPageVO.setAge(DateUtils.getAge(portrait.getBirthDate()));
//                            }
//                            if (UtilValidate.isNotEmpty(portrait.getUrl())) {
//                                warningPageVO.setFaceUrl(portrait.getUrl());
//                            }
//                            if (UtilValidate.isNotEmpty(portrait.getSex())) {
//                                warningPageVO.setSex(SEXEnums.getTypeByValue(portrait.getSex().toString()).name);
//                            }
//                            if (UtilValidate.isNotEmpty(portrait.getIdCard())) {
//                                warningPageVO.setIdCard(portrait.getIdCard());
//                            }
//                        }
//                    } else {
//                        warningPageVO.setScore(0.0);
//                    }
//                    warningPageVO.setPositionVO(apiFaceVO.getFaceRect());
//                    warningPageVO.setTime(a.getDate());
//                    //查询摄像头信息2-2
//                    if (!a.getCameraId().toString().equals("0")) {
//                        FaceCameraInfo faceCameraInfo = faceCameraService.findById(new Long(a.getCameraId()));
//                        String cameraId = a.getCameraId();
//                        warningPageVO.setCameraId(cameraId);
//                        warningPageVO.setCameraRegion((!UtilValidate.isEmpty(faceCameraInfo) ? faceCameraInfo.getCameraName() : cameraId));
//                    }
//                    ararmList.add(warningPageVO);
//                }
//            });
//            Page pages = new Page<>();
//            pages.setRecords(ararmList);
//            pages.setTotal(wvo.getPage().getTotal());
//            wvo = null;
//            warningVO = null;
////            System.out.println("耗时："+(System.currentTimeMillis()-time));
//            return successResult(pages);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return failResult("查询异常：" + e.getMessage());
//        }
       //System.out.println(apiAlarmVO);
        QueryWrapper<FaceInformation> queryWrapper=new QueryWrapper<>();
        if(UtilValidate.isNotEmpty(apiAlarmVO.getPage().getStartTimestamp())
                &&UtilValidate.isNotEmpty(apiAlarmVO.getPage().getStopTimestamp())) {
            SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            String start = dateFormatGmt.format(apiAlarmVO.getPage().getStartTimestamp());
            String end   = dateFormatGmt.format(apiAlarmVO.getPage().getStopTimestamp());
            System.out.println("strat:" + start);
            System.out.println("end:" + end);
//            queryWrapper.ge("time",start)
//                    .le("time",end);
            queryWrapper.between("time",start,end);
            if(UtilValidate.isNotEmpty(apiAlarmVO.getCameraIds())){
                //由于数据库中存储的cameraId实际为taskId，故如此查询
                queryWrapper.eq("cameraId",apiAlarmVO.getTaskIds().get(0));
            }
        }
//        queryWrapper.orderByDesc("time");
        Page <FaceInformation>pages = new Page<>();
        pages.setCurrent(apiAlarmVO.getPage().getPageNo());
        pages.setSize(apiAlarmVO.getPage().getPageSize());
        IPage<FaceInformation> faceInformations = faceInformationMapper.selectPage(pages,queryWrapper);
        //System.out.println(faceInformations.getRecords());
        Integer faceInformationsNumber = 0;
        faceInformationsNumber = faceInformationMapper.selectCount(queryWrapper);
        pages.setRecords(faceInformations.getRecords());
        pages.setTotal(faceInformationsNumber);
        //System.out.println(pages);
        return successResult(pages);
    }

    @ApiOperation(value = "获取全部布控任务中的摄像头信息和最近一条预警信息")
    @GetMapping(value = "/getCameraWarningByTask")
    public CommonResult findCameraByTask() {
        List<FaceCameraEntity> all = faceCameraService.findCameraByTask();
        if (UtilValidate.isEmpty(all)) {
            return successResult(new ArrayList<>());
        }
//        CameraWarningVO
        List<CameraWarningVO> myList = new ArrayList<>();
        all.forEach(e ->
        {
            CameraWarningVO cameraWarningVO = new CameraWarningVO();
            CameraVO cameraVO = new CameraVO();
            BeanUtils.copyProperties(e, cameraVO);
            cameraWarningVO.setCamera(cameraVO);
            cameraWarningVO.setWarning(getWarningByCameraId(e));
            myList.add(cameraWarningVO);
        });
        return successResult(myList);
    }

    /**
     * 根據攝像頭获取最新的摄像头id
     *
     * @param
     * @return
     */
    private WarningPageVO getWarningByCameraId(FaceCameraEntity faceCameraEntity) {
        ApiAlarmVO apiAlarmVO = new ApiAlarmVO();
        PageVO page = new PageVO();
        page.setPageSize(1);
        apiAlarmVO.setPage(page);
        apiAlarmVO.setCameraIds(Arrays.asList(faceCameraEntity.getIdFaceCamera().toString()));
        ApiVO warningVO = (ApiVO) httpUtil.post(link + ApiUrlEnum.ALARMS_POSTURL.getUrl(), apiAlarmVO, ApiVO.class);
        if (UtilValidate.isEmpty(warningVO) || warningVO.getCode().intValue() == ErrEnum.NOT_FOUND.getCode().intValue()) {
            return new WarningPageVO();
        }
        if (warningVO.getCode().intValue() != ErrEnum.OK.getCode().intValue()) {
            return new WarningPageVO();
        }
        WarningBayonetReturnVO wvo = gson.fromJson(gson.toJson(warningVO.getData()), WarningBayonetReturnVO.class);
        if (UtilValidate.isEmpty(wvo)) {
            return new WarningPageVO();
        }
        List<WarningPageVO> ararmList = new ArrayList<>();
        wvo.getResult().forEach(a ->
        {
            if (!UtilValidate.isEmpty(a.getFaces()) && a.getFaces().size() > 0) {
                ApiFaceVO apiFaceVO = a.getFaces().get(0);
                try {
                    if (redisUtils.exists(RedisKeys.getCameraSize(a.getCameraId()))) {
                        BgImageSize bgImageSize = gson.fromJson(redisUtils.get(RedisKeys.getCameraSize(a.getCameraId())).toString(), BgImageSize.class);
                        PositionVO positionVo = Base64ImageUtils.deelPostion(apiFaceVO.getFaceRect(), bgImageSize.getBgWidth(), bgImageSize.getBgHeight());
                        positionVo.setBgHeight(bgImageSize.getBgWidth());
                        positionVo.setBgWidth(bgImageSize.getBgHeight());
                        apiFaceVO.setFaceRect(positionVo);
                    } else {

                        Integer width = 1080;
                        Integer height = 607;
                        Boolean mark = true;
                        try {
                            BufferedImage bufferedImage = Base64ImageUtils.urlToBufferImage(new URL(a.getFaceBgUrl()));
                            if (UtilValidate.isNotEmpty(bufferedImage)) {
                                width = bufferedImage.getWidth();
                                height = bufferedImage.getHeight();
                            }
                        } catch (Exception e2) {
                            mark = false;
                        }
                        //   "{\"cameraId\":\"1211828378753777666\",\"bgWidth\":1080,\"bgHeight\":607}"
                        PositionVO positionVo = Base64ImageUtils.deelPostion(apiFaceVO.getFaceRect(), width, height);
                        positionVo.setBgHeight(height);
                        positionVo.setBgWidth(width);
                        apiFaceVO.setFaceRect(positionVo);
                        if (mark) {
                            redisUtils.set(RedisKeys.getCameraSize(a.getCameraId()), gson.toJson(new BgImageSize(a.getCameraId(), width, height)));
                        }
                    }
                } catch (Exception e1) {
                }
                WarningPageVO warningPageVO = new WarningPageVO();
                //根据任务区查询3
                //测试后期需要删除 TODO
                QueryWrapper<ControlTask> queryWrapper = new QueryWrapper<>();
                ControlTask controlTask = new ControlTask();
                controlTask.setTaskNo(a.getTaskId());
                queryWrapper.setEntity(controlTask);
                List<ControlTask> controlTaskList = iControlTaskService.getBaseMapper().selectList(queryWrapper);
                warningPageVO.setTaskId(a.getTaskId());
                if (!UtilValidate.isEmpty(controlTaskList) && controlTaskList.size() >= 1) {
                    controlTask = controlTaskList.get(0);
                    warningPageVO.setTaskName(controlTask.getTaskName());
                    warningPageVO.setTaskType(controlTask.getDisposalType());
                } else {
                    warningPageVO.setTaskName("任务已删除");
                    warningPageVO.setTaskType("");
                }
                //基本展示信息4-4
                warningPageVO.setBgImg(a.getFaceBgUrl());

                if (!UtilValidate.isEmpty(apiFaceVO.getCompare()) && apiFaceVO.getCompare().size() > 0) {
                    ComparisonVO comparisonVO = apiFaceVO.getCompare().get(0);
                    //库名称和库id0-2
                    FaceLibrary faceLibrary = iFaceLibraryService.getBaseMapper().selectById(comparisonVO.getLibraryId());
                    warningPageVO.setLibId(comparisonVO.getLibraryId());
                    if (!UtilValidate.isEmpty(faceLibrary)) {
                        warningPageVO.setLibName(faceLibrary.getFactoryName());
                    } else {
                        warningPageVO.setLibName(comparisonVO.getLibraryId());
                    }
                    warningPageVO.setScore(comparisonVO.getHitSimilarity());
                    //查询人员信息 5-5
                    Portrait portrait = iPortraitService.getById(comparisonVO.getComparisonFaceId());
                    if (!UtilValidate.isEmpty(portrait)) {
                        if (UtilValidate.isNotEmpty(portrait.getName())) {
                            warningPageVO.setName(portrait.getName());
                        }
                        if (UtilValidate.isNotEmpty(portrait.getBirthDate())) {
                            warningPageVO.setAge(DateUtils.getAge(portrait.getBirthDate()));
                        }
                        if (UtilValidate.isNotEmpty(portrait.getUrl())) {
                            warningPageVO.setFaceUrl(portrait.getUrl());
                        }
                        if (UtilValidate.isNotEmpty(portrait.getSex())) {
                            warningPageVO.setSex(SEXEnums.getTypeByValue(portrait.getSex().toString()).name);
                        }
                        if (UtilValidate.isNotEmpty(portrait.getIdCard())) {
                            warningPageVO.setIdCard(portrait.getIdCard());
                        }
                    }
                } else {
                    warningPageVO.setScore(0.0);
                }
                warningPageVO.setPositionVO(apiFaceVO.getFaceRect());
                warningPageVO.setTime(a.getDate());
                //查询摄像头信息2-2
                if (!a.getCameraId().toString().equals("0")) {
                    warningPageVO.setCameraId(faceCameraEntity.getIdFaceCamera().toString());
                    warningPageVO.setCameraRegion(faceCameraEntity.getCameraName());
                }
                ararmList.add(warningPageVO);
            }
        });
        if (ararmList.size() > 0) {
            return ararmList.get(0);
        }
        return new WarningPageVO();
    }


    @GetMapping("/taskStatus/{taskId}")
    @ApiParam(required = true, name = "taskStatus", value = "")
    @ApiOperation(value = "查看任务状态")
    public CommonResult CommonResult(@PathVariable("taskId") String taskId) {
        if (UtilValidate.isEmpty(taskId)) {
            return failResult(SystemCode.ParaIsNull);
        }

//        //开发完成够对接 TODO
//        ControlTask controlTask = iControlTaskService.getById(taskId);
//        if(UtilValidate.isEmpty(controlTask))
//        {
//            return failResult("没有找到对应的任务");
//        }

        ApiVO warningVO = (ApiVO) httpUtil.get(link + ApiUrlEnum.ALARMS_STATUS.getUrl() + "/" + taskId, ApiVO.class);
        if (UtilValidate.isEmpty(warningVO) || warningVO.getCode() != ErrEnum.OK.getCode().intValue() || UtilValidate.isEmpty(warningVO.getData())) {
            return failResult("查询任务状态出错");
        }
        Map myMap = gson.fromJson(gson.toJson(warningVO.getData()), Map.class);
//        Map myMap=new HashMap();
//        myMap.put("status","STATUS_OVER");
        return successResult(myMap);
    }

    @GetMapping("/taskInfo/{carmeraId}")
    @ApiParam(required = true, name = "taskName", value = "")
    @ApiOperation(value = "根据摄像头id查看任务信息")
    public CommonResult taskInfo(@PathVariable("carmeraId") String carmeraId) {
        if (UtilValidate.isEmpty(carmeraId)) {
            return failResult(SystemCode.ParaIsNull);
        }
        ControlTask controlTask = iControlTaskService.getTaskInfoByCameraID(carmeraId);
        if (UtilValidate.isEmpty(controlTask)) {
            return failResult(SystemCode.NO_DATA);
        }
        return successResult(controlTask);
    }


}
